<?php

namespace app\admin\jobs;

use app\admin\model\Order;
use app\admin\model\OrderPayment;
use app\common\service\CompleteNotificationService;
use app\common\service\Mail;
use think\facade\Log;

class TimeoutCancelOrder
{

    private $order_model;
    private $order_payment_model;
    private $order_timeout_time;

    public function __construct()
    {
        $this->order_model = new Order();
        $this->order_payment_model = new OrderPayment();
        $this->order_timeout_time =  env('ORDER_TIMEOUT_TIME', 48 * 3600);
    }
    /**
     * @describe
     * @author: Bobo
     * @date: 2025-07-17 14:43:35 
     * @param [type] @required
     * @return Renderable
     */
    public function execute()
    {
        try {
            $order_list = $this->order_model
                ->whereIn('status', [10, 21]) // 订单状态为待支付或审核通过待支付
                ->where('pay_status', 1) // 支付状态为未支付
                ->where('create_time', '<', date('Y-m-d H:i:s', time() - $this->order_timeout_time))
                ->order('create_time', 'desc')
                ->select();

            // 如果订单列表为空，则直接返回
            if (empty($order_list)) {
                return;
            }

            $completeNotificationService = new CompleteNotificationService();
            $mailService = new Mail();

            // 遍历订单列表，将订单状态改为已取消，将支付状态改为已取消
            foreach ($order_list as $item) {
                try {
                    // 更新订单状态
                    $updateResult = $this->order_model->where('id', $item->id)->update([
                        'status' => 70,
                        'update_time' => date('Y-m-d H:i:s')
                    ]);

                    if (!$updateResult) {
                        throw new \Exception("更新订单状态失败，订单ID: {$item->id}");
                    }

                    // 发送邮件
                    try {
                        $email_res = $mailService->send('order_cancel_timeout', $item->toArray());
                        if (!$email_res) {
                            // 记录邮件发送失败，但不中断流程
                            Log::error("订单超时取消邮件发送失败，订单ID: {$item->id}");
                        }
                    } catch (\Exception $emailException) {
                        // 记录邮件发送异常，但不中断流程
                        Log::error("订单超时取消邮件发送异常，订单ID: {$item->id}, 错误: " . $emailException->getMessage());
                    }

                    // 发送钉钉通知
                    try {
                        $partner = $item->partner ? explode(',', $item->partner) : [];
                        $recipients = array_unique([$item->owner, ...$partner]);
                        $order_type = $item->order_category == 'wholesal' ? '存入资产' : '普通';
                        $content = "您负责的{$order_type}订单由于超过支付时间未支付，已自动取消，请及时跟进\n\n";
                        $res = $completeNotificationService->send('order_cancel', $item->toArray(), $recipients, $content);

                        if (!$res) {
                            // 记录钉钉通知发送失败，但不中断流程
                            Log::error("订单超时取消钉钉通知发送失败，订单ID: {$item->id}");
                        }
                    } catch (\Exception $notificationException) {
                        // 记录钉钉通知发送异常，但不中断流程
                        Log::error("订单超时取消钉钉通知发送异常，订单ID: {$item->id}, 错误: " . $notificationException->getMessage());
                    }
                } catch (\Exception $itemException) {
                    // 记录单个订单处理异常，继续处理下一个订单
                    Log::error("处理超时订单异常，订单ID: {$item->id}, 错误: " . $itemException->getMessage());
                    continue;
                }
            }
        } catch (\Exception $e) {
            // 记录整体执行异常
            Log::error("TimeoutCancelOrder execute 方法执行异常: " . $e->getMessage());
            Log::error("异常堆栈: " . $e->getTraceAsString());
            throw $e; // 重新抛出异常，让上层处理
        }
    }
}
